package net.tngou.crawler.drug;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import net.tngou.c4j.util.HttpUtil;
import net.tngou.cache.CacheEngine;
import net.tngou.cache.TgCacheEngine;
import net.tngou.crawler.util.StringUtil;

/**
 * 健客网
 * @author tngou@tngou.net
 *
 */
public class Com_Jianke extends BaseCrawler implements CrawlerDrug{
	private static final Logger log= LoggerFactory.getLogger(Com_Jianke.class);
	
	private String url="https://www.jianke.com/product/{}.html";
	private String purl="https://www.jianke.com/wcgi/promos/promos/app/";



	@Override
	public JSONObject getJson(URL url) {
		log.info("请求页面:{}",url.toString());
		Document doc = HttpUtil.get(url.toString());
		if(doc==null||doc.getElementById("b_2_2")==null)return null;
		json.put("url", url.toString());
		json.put("onlinepharmacy", onlinepharmacy);
		//唯一值
		String[] uns = url.toString().split("/");
		json.put("un",uns[uns.length-1].replaceAll(".html", "-").split("-")[0]);
		//标签
		Elements crumb_p = doc.getElementsByClass("crumb_p");		
		if(crumb_p.first()!=null)
		{
			Elements as = crumb_p.first().getElementsByTag("a");
			List<String> list = new ArrayList<>();
			for (int i = 1; i < as.size()-1; i++) {
				list.add(as.get(i).text());
			}				
			json.put("tag", list);
		}
		//图片
		Elements smallPic = doc.getElementsByClass("pro_pic_li");
		if(smallPic.first()!=null)
		{
			Elements imgs = smallPic.first().getElementsByTag("a");
			List<String> list = new ArrayList<>();
			imgs.forEach(e->{
				String rel = e.attr("rel");
				JSONObject object =(JSONObject) JSON.parse(rel);
				String src = object.getString("largeimage");
				if(StringUtil.isNotEmpty(src))
				{
					list.add(src);
				}
			});
			json.put("picture", list);
		}
		//价格		
		json.put("price", getPrice(json.getString("un")));
		
		//类型

		//说明书
		Element instruction = doc.getElementById("b_2_2");
		if(instruction!=null)
		{
			JSONObject instructions = instructions_s(instruction.getElementsByTag("p").text());
			
			json.put("instructions",instructions );
		}
		return json;
	}
	
	public float getPrice(String itemid) {
		String rs = HttpUtil.getString(purl+itemid);
		if(rs!=null)
		{	
			JSONObject rjs = (JSONObject) JSON.parse(rs);
			if(rjs!=null)
			{
				JSONObject data = rjs.getJSONObject("item");
				if(data!=null)
				return (float) (data.getFloatValue("price")/100);
			}
		
		}
		return 0;
	}
	

}

